<template>
  <BasicModal @register="registerModal" title="从数据库导入表单" :width="500" :confirmLoading="confirmLoading" @cancel="handleCancel">
    <template #footer>
      <a-button @click="handleCancel">关闭</a-button>
      <a-button type="primary" @click="handleTrans" preIcon="ant-design:swap" :loading="confirmLoading || btnLoading">生成表单</a-button>
    </template>
    <template #default>
      <a-spin :spinning="confirmLoading">
        <BasicTable @register="registerTable" :rowSelection="rowSelection" :onTableRedo="queryTables">
          <template #tableTitle>
            <div>
              注：导入表会排除配置前缀表
              <a href="#" target="_blank">参考文档</a>
            </div>
          </template>
        </BasicTable>
      </a-spin>
    </template>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref } from 'vue';
  import { defHttp } from '/@/utils/http/axios';
  import { BasicTable } from '/@/components/Table';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { useListTable } from '/@/hooks/system/useListPage';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'TransDb2Online',
    components: { BasicModal, BasicTable },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const { createMessage: $message } = useMessage();
      const emptyText = ref('暂无数据');
      const confirmLoading = ref(false);
      const btnLoading = ref(false);
      const metaSource = ref([]);
      const dataSource = ref([]);
      const [registerModal, { closeModal }] = useModalInner(() => {
        btnLoading.value = false;
        emptyText.value = '暂无数据';
        selectedRowKeys.value = [];
        queryTables();
      });
      const [registerTable, { setPagination }, { rowSelection, selectedRowKeys }] = useListTable({
        bordered: true,
        columns: [{ title: '表名', align: 'left', dataIndex: 'id' }],
        dataSource,
        maxHeight: 300,
        locale: { emptyText },
        pagination: {
          showQuickJumper: false,
          showSizeChanger: false,
        },
        clickToRowSelect: true,
        showIndexColumn: true,
        showActionColumn: false,
        formConfig: {
          schemas: [
            {
              label: '表名',
              field: 'tableName',
              component: 'Input',
              componentProps: {
                style: { width: '100%' },
                placeholder: '请输入表名以模糊筛选',
                onChange: (e) => searchFilter(e.target.value),
              },
              disabledLabelWidth: true,
              itemProps: {
                labelCol: { sm: 24, md: 4 },
                wrapperCol: { sm: 24, md: 20 },
              },
            },
          ],
          baseColProps: { xs: 24, sm: 24, md: 24, lg: 24, xl: 24, xxl: 24 },
          showActionButtonGroup: false,
        },
      });
      function queryTables() {
        confirmLoading.value = true;
        return defHttp
          .get(
            {
              url: '/api-online/online/cgform/head/queryTables',
            },
            {
              errorMessageMode: 'none',
            }
          )
          .then(
            (result) => {
              dataSource.value = result;
              metaSource.value = [...result];
              return result;
            },
            (e) => {
              if (e.message == 'noadminauth') {
                emptyText.value = '非admin用户无权限操作！';
                $message.warn(emptyText.value);
              } else {
                console.error(e);
              }
              dataSource.value = [];
              metaSource.value = [];
            }
          )
          .finally(() => {
            confirmLoading.value = false;
          });
      }
      function searchFilter(keyword) {
        if (metaSource.value.length === 0) return;
        if (!keyword) {
          dataSource.value = [...metaSource.value];
        } else {
          dataSource.value = metaSource.value.filter((item) => item.id.toLowerCase().includes(keyword.toLowerCase()));
          emptyText.value = dataSource.value.length === 0 ? '无筛选结果' : '暂无数据';
        }
        setPagination({ current: 1 });
      }
      function handleCancel() {
        closeModal();
      }
      function handleTrans() {
        if (!selectedRowKeys.value || selectedRowKeys.value.length == 0) {
          $message.warning('请选择一张表');
          return;
        } else {
          btnLoading.value = true;
          let tbNames = selectedRowKeys.value.join(',');
          defHttp
            .post({ url: '/api-online/online/cgform/head/transTables/' + tbNames })
            .then(() => {
              closeModal();
              emit('success');
            })
            .finally(() => (btnLoading.value = false));
        }
      }
      return {
        emptyText,
        confirmLoading,
        btnLoading,
        metaSource,
        handleTrans,
        handleCancel,
        queryTables,
        registerModal,
        registerTable,
        rowSelection,
        selectedRowKeys,
      };
    },
  });
</script>
<style scoped></style>
